package com.runfast.common.utils;

import com.runfast.common.web.entity.Result;
import com.runfast.common.web.entity.ResultCode;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.ui.ModelMap;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

/**
 * @author: lijin
 * @date: 2018年05月28日
 */
public class SingleSendSms {

    private final static String APP_KEY = "23476026"; //AppKey从控制台获取
    private final static String APP_SECRET = "53aabb325c6b2dc70803cda1d0410cdb"; //AppSecret从控制台获取
    private final static String SIGN_NAME = "跑腿快车"; // 签名名称从控制台获取，必须是审核通过的
    //    private final static String TEMPLATE_CODE = "SMS_17020084"; //模板CODE从控制台获取，必须是审核通过的
    private final static String HOST = "sms.market.alicloudapi.com"; //API域名从控制台获取

    private final static String appcode = "70118048691549cabc7c31a719c85b5a";

    private final static String ERRORKEY = "errorMessage";  //返回错误的key

    public static Result sendMsg(String phoneNum, String params, String template_code) {

        ModelMap modelMap = new ModelMap();
        BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager(
                RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
                        .register("https", SSLConnectionSocketFactory.getSocketFactory())
                        .build(),
                null,
                null,
                null
        );
        HttpClient httpClient = HttpClientBuilder.create()
                .setConnectionManager(connManager)
                .build();

        String url = "http://api.zthysms.com/sendSms.do";
        HttpPost httpPost = new HttpPost(url);

        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(2000).build();
        httpPost.setConfig(requestConfig);

        ArrayList<NameValuePair> postParams = new ArrayList<>();
        postParams.add(new BasicNameValuePair("username", "ptkc888hy"));
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String formatDate = dateFormat.format(new Date());
        postParams.add(new BasicNameValuePair("tkey", formatDate));

        String password = "nbujTx";

        postParams.add(new BasicNameValuePair("password", DigestUtils.md5Hex(DigestUtils.md5Hex(password).toString().toLowerCase()+formatDate).toString().toLowerCase()));
        postParams.add(new BasicNameValuePair("mobile", phoneNum));

        try {
            Map paramsMap = JsonUtils.getMapper().readValue(params, Map.class);
            Object code = paramsMap.get("code");

            String template = "【跑腿快车】你的验证码为：${code}，有效时间为5分钟，请尽快使用。";
            if("SMS_17020084".equals(template_code)){
                template = "【跑腿快车】你的验证码为：${code}，有效时间为5分钟，请尽快使用。";
                template = template.replace("${code}",code.toString());
            }else if("SMS_47920224".equals(template_code)){
                template = "【跑腿快车】你的密码已重置为：${passwd}，请使用新密码登录";
                template = template.replace("${passwd}",code.toString());
            }
            postParams.add(new BasicNameValuePair("content", template));

            UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(postParams,"utf-8");
//            httpPost.addHeader("Content-Type", "text/plain");
            httpPost.setEntity(postEntity);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            String s = EntityUtils.toString(httpEntity, "UTF-8");
            System.out.println("=============短信请求参数："+params+"==================");
            System.out.println("=============短信返回结果："+s+"==================");
            if(s.startsWith("1,")){
                return Result.ok("短信发送成功");
            }else{
                return Result.fail(ResultCode.FAIL, s);
            }
        }catch (Exception e){

            e.printStackTrace();;
            return Result.fail(ResultCode.FAIL, e.getMessage());
        }

    }
}
